package com.symaster.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author yinmiao
 * @date 2021-07-17 09:06
 */
public class DNSUtil {

    public static void main(String[] args) throws IOException {
        String baidu = getCurrentHostIP();
        System.out.println(baidu);
    }

    /**
     * 获取当前主机公网IP
     */
    public static String getCurrentHostIP() throws IOException {

        try {
            String ipAddress = baiduBce();
            if (StringUtils.isNotEmpty(ipAddress)) {
                return ipAddress;
            }
        } catch (Exception ignored) {
        }

        try {
            String ipAddress = jsonIp();
            if (StringUtils.isNotEmpty(ipAddress)) {
                return ipAddress;
            }
        } catch (Exception ignored) {
        }

        throw new IOException("获取主机公网IP失败");
    }

    private static String jsonIp() throws IOException {
        HttpGet httpGet = new HttpGet("https://jsonip.com/");
        String response = CommonUtil.executeRequest(httpGet, StandardCharsets.UTF_8);
        if (StringUtils.isEmpty(response)) {
            return null;
        }

        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getString("ip");
    }

    private static String baiduBce() throws IOException {
        HttpGet httpGet = new HttpGet("https://qifu-api.baidubce.com/ip/local/geo/v1/district");
        String response = CommonUtil.executeRequest(httpGet, StandardCharsets.UTF_8);
        if (StringUtils.isEmpty(response)) {
            return null;
        }

        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getString("ip");
    }
}
